<template>
  <a-upload
      v-model:file-list="fileList"
      name="file"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :action="action"
      :before-upload="beforeUpload"
      @change="handleChange"
  >
    <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 100%;" />
    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
      <div class="ant-upload-text">Upload</div>
    </div>
  </a-upload>
</template>

<script>

  import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'

  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  export default {
    name: "single-image-upload",
    components: {
      PlusOutlined,
      LoadingOutlined,
    },
    props: {
      src: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        fileList: [],
        loading: false,
        imageUrl: this.src,
        // action: process.env.VUE_APP_API_PROXY_TARGET + '/api/minio/upload-things-image-file'
        action: '/api/minio/upload-things-image-file'
      }
    },
    methods: {
      beforeUpload (file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/svg+xml'

        if (!isJpgOrPng) {
          this.$message.error('You can only upload JPG file!');
        }

        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isLt2M) {
          this.$message.error('Image must smaller than 2MB!');
        }

        return isJpgOrPng && isLt2M;
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true;
          return;
        }

        if (info.file.status === 'done') {
          // Get this url from response in real world.
          // getBase64(info.file.originFileObj, base64Url => {
          //   this.imageUrl.value = base64Url;
          //   this.loading.value = false;
          // });

          this.imageUrl = info.file.response.data
          this.$emit('update:src', info.file.response.data)
          this.loading = false
        }

        if (info.file.status === 'error') {
          this.loading.value = false;
          this.$message.error('upload error');
        }
      },
    }
  }
</script>

<style scoped>

  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

</style>
